package com.fxm.config;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Aspect
@Order(0)
@Component
@Slf4j
public class ControllerAspect {
    ThreadLocal<Long> startTime = new ThreadLocal<>();

    @Pointcut("@within(org.springframework.web.bind.annotation.RestController)")
    public void doRequest() {
    }

    @Before("doRequest()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {

        startTime.set(System.currentTimeMillis());
        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String url = request.getRequestURL().toString();
        String method = request.getMethod();
        String args = "";
        if (joinPoint.getArgs() != null) {
            try {
                args = JSON.toJSONString(joinPoint.getArgs());
            } catch (Exception e) {
                log.error("error:{}",e.getMessage());
            }
        }
        log.info("url:{}, method:{},args:{}", url, method, args);
    }

    @AfterReturning(returning = "ret", pointcut = "doRequest()")
    public void doAfterReturning(Object ret) throws Throwable {
        // 处理完请求，返回内容
        log.info("RESPONSE : {}",  JSON.toJSONString(ret));
        log.info("SPEND TIME : " + (System.currentTimeMillis() - startTime.get()));
        startTime.remove();
    }


}
